﻿using EquipmentAlarmSystem.Service.Library;
using EquipmentAlarmSystem.Service.Models;
using EquipmentAlarmSystem.Service.OperationManagementUnit;
using Microsoft.AspNetCore.Mvc;
using System.Text.Encodings.Web;
using System.Text.Json;

namespace EquipmentAlarmSystem.Controllers;

/// <summary>
/// 设备管理
/// </summary>
[ApiController]
[Route("[controller]/[action]")]
public class EquipmentController : Controller
{
    private readonly ILogger<EquipmentController> _logger;

    public EquipmentController(ILogger<EquipmentController> logger)
    {
        _logger = logger;
    }

    /// <summary>
    /// 获取配置文件
    /// </summary>
    /// <returns></returns>
    [HttpGet]
    public string GetEquipment(string id)
    {
        return Basics.GetEquipmentConfiguration(id);
    }

    /// <summary>
    /// 修改配置文件
    /// </summary>
    /// <param name="configure"></param>
    /// <returns></returns>
    [HttpPost]
    public string ModifyEquipmentSiemensS7(DeviceInformationSiemensS7 configure)
    {
        return Basics.ModifEquipmentConfiguration(configure);
    }

    /// <summary>
    /// 修改配置文件
    /// </summary>
    /// <param name="configure"></param>
    /// <returns></returns>
    [HttpPost]
    public string ModifyEquipmentModusTcp(DeviceInformationModusTcp configure)
    {
        return Basics.ModifEquipmentConfiguration(configure);
    }

    /// <summary>
    /// 开启设备
    /// </summary>
    /// <returns></returns>
    [HttpGet()]
    public string Open(string id)
    {
        if (Management.RunningServicesId.Contains(id) == false)
        {
            Management management = new();

            return management.ActivateDeviceService(id);
        }
        return "服务已经在运行，无需重复激活";
    }

    /// <summary>
    /// 关闭设备
    /// </summary>
    /// <returns></returns>
    [HttpGet()]
    public string Close(string id)
    {
        Management.EndDeviceService(id);

        return $"{id} 设备服务关闭中";
    }

    /// <summary>
    /// 获取设备运行列表
    /// </summary>
    /// <returns></returns>
    [HttpGet]
    public string GetEquipmentOperationList()
    {
        return JsonSerializer.Serialize(Management.RunningServicesId, new JsonSerializerOptions()
        {
            Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping
        });
    }
}
